package org.luxor.common.netty.protocol.handler.connect;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.luxor.common.netty.config.properties.NettyClientProperties;
import org.luxor.common.netty.constant.NettyReasonCode;
import org.luxor.common.netty.exception.NettyTransportException;
import org.luxor.common.netty.protocol.message.NettyConnAckMessage;
import org.luxor.common.netty.protocol.message.NettyConnectMessage;


/**
 * 建立确定
 *
 * @author Mr.yan @date 2023/12/8
 */
public class ConnAckMessageHandler extends SimpleChannelInboundHandler<NettyConnAckMessage> {
    private final NettyClientProperties nettyClientProperties;

    public ConnAckMessageHandler(NettyClientProperties nettyClientProperties) {
        this.nettyClientProperties = nettyClientProperties;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String clientId = nettyClientProperties.getId();
        ctx.channel().attr(ConnectMessageHandler.CLIENT_IDENTIFIER_ATTRIBUTE_KEY).set(clientId);
        if (nettyClientProperties.getAuth() == null) {
            ctx.writeAndFlush(NettyConnectMessage.from(clientId));
        } else {
            String username = nettyClientProperties.getAuth().getUsername();
            String password = nettyClientProperties.getAuth().getPassword();
            ctx.writeAndFlush(NettyConnectMessage.from(clientId, username, password));
        }
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, NettyConnAckMessage nettyConnAckMessage) throws Exception {
        int reasonCode = nettyConnAckMessage.variableHeader().reasonCode();
        String reasonMsg = nettyConnAckMessage.variableHeader().reasonMsg();
        if (NettyReasonCode.SUCCESS.code() != reasonCode) {
            throw new NettyTransportException(reasonCode, reasonMsg);
        }
    }
}
